package org.example.com.controller;

import org.example.com.pojo.Post;
import org.example.com.pojo.Result;
import org.example.com.pojo.vo.PostVO;
import org.example.com.service.PostService;
import org.example.com.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 帖子Controller
 */
@RestController
@RequestMapping("/api/discover/posts")
public class PostController {
    
    @Autowired
    private PostService postService;
    
    /**
     * 创建帖子
     */
    @PostMapping
    public Result createPost(@RequestBody Map<String, Object> request) {
        try {
            // 获取当前用户信息
            Map<String, Object> claims = ThreadLocalUtil.get();
            Integer userId = (Integer) claims.get("id");
            String userName = (String) claims.get("name");
            String userAvatar = (String) claims.get("avatar");
            
            // 构建帖子对象
            Post post = new Post();
            post.setUserId(userId);
            post.setUserName(userName);
            post.setUserAvatar(userAvatar);
            post.setContent((String) request.get("content"));
            post.setPrivacy((String) request.get("privacy"));
            
            // 获取图片和话题标签
            @SuppressWarnings("unchecked")
            List<String> images = (List<String>) request.get("images");
            @SuppressWarnings("unchecked")
            List<String> topics = (List<String>) request.get("topics");
            
            // 创建帖子
            Post createdPost = postService.createPost(post, images, topics);
            
            Map<String, Object> response = new HashMap<>();
            response.put("code",0);
            response.put("postId", createdPost.getId());
            response.put("message", "帖子发布成功");
            
            return Result.success(response);
        } catch (Exception e) {
            return Result.error("发布失败：" + e.getMessage());
        }
    }
    
    /**
     * 分页查询帖子列表
     */
    @GetMapping
    public Result getPosts(@RequestParam(defaultValue = "1") Integer page,
                          @RequestParam(defaultValue = "10") Integer limit) {
        try {
            // 获取当前用户ID（可能为null，表示未登录）
            Integer currentUserId = null;
            try {
                Map<String, Object> claims = ThreadLocalUtil.get();
                currentUserId = (Integer) claims.get("id");
            } catch (Exception e) {
                // 未登录用户，currentUserId保持为null
            }
            
            List<PostVO> posts = postService.getPosts(page, limit, currentUserId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("posts", posts);
            response.put("page", page);
            response.put("limit", limit);
            response.put("total", posts.size());
            
            return Result.success(response);
        } catch (Exception e) {
            return Result.error("获取帖子列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据用户ID查询帖子列表
     */
    @GetMapping("/user/{userId}")
    public Result getPostsByUserId(@PathVariable Integer userId,
                                  @RequestParam(defaultValue = "1") Integer page,
                                  @RequestParam(defaultValue = "10") Integer limit) {
        try {
            // 获取当前用户ID（可能为null，表示未登录）
            Integer currentUserId = null;
            try {
                Map<String, Object> claims = ThreadLocalUtil.get();
                currentUserId = (Integer) claims.get("id");
            } catch (Exception e) {
                // 未登录用户，currentUserId保持为null
            }
            
            List<PostVO> posts = postService.getPostsByUserId(userId, page, limit, currentUserId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("posts", posts);
            response.put("page", page);
            response.put("limit", limit);
            response.put("total", posts.size());
            
            return Result.success(response);
        } catch (Exception e) {
            return Result.error("获取用户帖子列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据ID查询帖子详情
     */
    @GetMapping("/{id}")
    public Result getPostById(@PathVariable Integer id) {
        try {
            // 获取当前用户ID（可能为null，表示未登录）
            Integer currentUserId = null;
            try {
                Map<String, Object> claims = ThreadLocalUtil.get();
                currentUserId = (Integer) claims.get("id");
            } catch (Exception e) {
                // 未登录用户，currentUserId保持为null
            }
            
            PostVO post = postService.getPostById(id, currentUserId);
            if (post == null) {
                return Result.error("帖子不存在");
            }
            
            return Result.success(post);
        } catch (Exception e) {
            return Result.error("获取帖子详情失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新帖子
     */
    @PutMapping("/{id}")
    public Result updatePost(@PathVariable Integer id, @RequestBody Map<String, Object> request) {
        try {
            // 获取当前用户信息
            Map<String, Object> claims = ThreadLocalUtil.get();
            Integer userId = (Integer) claims.get("id");
            
            // 构建帖子对象
            Post post = new Post();
            post.setId(id);
            post.setUserId(userId);
            post.setContent((String) request.get("content"));
            post.setPrivacy((String) request.get("privacy"));
            
            // 获取图片和话题标签
            @SuppressWarnings("unchecked")
            List<String> images = (List<String>) request.get("images");
            @SuppressWarnings("unchecked")
            List<String> topics = (List<String>) request.get("topics");
            
            // 更新帖子
            boolean success = postService.updatePost(post, images, topics);
            if (success) {
                return Result.success("帖子更新成功");
            } else {
                return Result.error("帖子更新失败");
            }
        } catch (Exception e) {
            return Result.error("更新失败：" + e.getMessage());
        }
    }
    
    /**
     * 删除帖子
     */
    @DeleteMapping("/{id}")
    public Result deletePost(@PathVariable Integer id) {
        try {
            // 获取当前用户信息
            Map<String, Object> claims = ThreadLocalUtil.get();
            @SuppressWarnings("unused")
            Integer userId = (Integer) claims.get("id");
            
            // 这里可以添加权限检查，确保只能删除自己的帖子
            // 暂时省略，实际项目中应该添加
            
            boolean success = postService.deletePost(id);
            if (success) {
                return Result.success("帖子删除成功");
            } else {
                return Result.error("帖子删除失败");
            }
        } catch (Exception e) {
            return Result.error("删除失败：" + e.getMessage());
        }
    }
    
    /**
     * 点赞帖子
     */
    @PostMapping("/{id}/like")
    public Result likePost(@PathVariable Integer id) {
        try {
            // 获取当前用户信息
            Map<String, Object> claims = ThreadLocalUtil.get();
            Integer userId = (Integer) claims.get("id");
            
            boolean success = postService.likePost(id, userId);
            if (success) {
                return Result.success("点赞成功");
            } else {
                return Result.error("点赞失败，可能已经点赞过了");
            }
        } catch (Exception e) {
            return Result.error("点赞失败：" + e.getMessage());
        }
    }
    
    /**
     * 取消点赞帖子
     */
    @DeleteMapping("/{id}/like")
    public Result unlikePost(@PathVariable Integer id) {
        try {
            // 获取当前用户信息
            Map<String, Object> claims = ThreadLocalUtil.get();
            Integer userId = (Integer) claims.get("id");
            
            boolean success = postService.unlikePost(id, userId);
            if (success) {
                return Result.success("取消点赞成功");
            } else {
                return Result.error("取消点赞失败");
            }
        } catch (Exception e) {
            return Result.error("取消点赞失败：" + e.getMessage());
        }
    }
    
    /**
     * 分享帖子
     */
    @PostMapping("/{id}/share")
    public Result sharePost(@PathVariable Integer id) {
        try {
            boolean success = postService.sharePost(id);
            if (success) {
                return Result.success("分享成功");
            } else {
                return Result.error("分享失败");
            }
        } catch (Exception e) {
            return Result.error("分享失败：" + e.getMessage());
        }
    }
}
